<template>
  <div class="send-mail-page">
    <el-page-header title="返回" content="发送邮件" @back="$router.back()">
    </el-page-header>
    <div class="card">
      <el-form
        ref="mailFormRef"
        :model="mailForm"
        :rules="formRules"
        label-position="top"
      >
        <el-form-item label="收件人" prop="recipient">
          <el-input
            v-model="mailForm.recipient"
            placeholder="请输入收件人UID"
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item label="邮件标题" prop="title">
          <el-input
            v-model="mailForm.title"
            placeholder="请输入邮件标题"
            :prefix-icon="Edit"
          />
        </el-form-item>
        <el-form-item label="邮件内容" prop="content">
          <el-input
            v-model="mailForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入邮件内容"
          />
        </el-form-item>

        <el-form-item label="附件">
          <div class="attachment-section">
            <div v-if="attachments.length > 0" class="attachment-list">
              <div
                v-for="(item, index) in attachments"
                :key="index"
                class="attachment-item"
              >
                <div class="item-info">
                  <el-icon class="item-icon"><Box /></el-icon>
                  <span class="item-name">{{ item.name }}</span>
                  <span class="item-count">x{{ item.count }}</span>
                </div>
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  circle
                  @click="removeAttachment(index)"
                  style="color: white !important"
                />
              </div>
            </div>

            <el-button
              type="primary"
              :icon="Plus"
              @click="showBagSelector = true"
              class="add-attachment-btn"
            >
              添加附件
            </el-button>
          </div>
        </el-form-item>

        <div class="center">
          <el-button
            type="success"
            size="large"
            :loading="sending"
            @click="sendMail"
            class="send-button"
          >
            <el-icon><Promotion /></el-icon>
            {{ sending ? "发送中..." : "发送邮件" }}
          </el-button>
        </div>
      </el-form>
    </div>

    <BagSelector
      v-model:visible="showBagSelector"
      :selected-items="attachments.map((att) => ({ id: att.id, count: att.count }))"
      @select-item="addAttachment"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { HandDrawnMessageBox } from "@/tool/handDrawnConfirm";
import { User, Edit, Box, Delete, Plus, Promotion } from "@element-plus/icons-vue";
import BagSelector from "@/components/BagSelector.vue";
import router from "@/router";
import { callApi } from "@/tool/server";
import { HandDrawnNotification } from "@/tool/handDrawnToast";

const mailForm = reactive({
  recipient: "",
  title: "",
  content: "",
});

const formRules = {
  recipient: [{ required: true, message: "请输入收件人UID", trigger: "blur" }],
  title: [{ required: true, message: "请输入邮件标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入邮件内容", trigger: "blur" }],
};

const attachments = ref<
  Array<{
    id: string;
    name: string;
    count: number;
    icon?: string;
    type: string;
  }>
>([]);

const mailFormRef = ref();
const showBagSelector = ref(false);
const sending = ref(false);

const addAttachment = (item: {
  id: string;
  name: string;
  count: number;
  icon?: string;
  type: string;
}) => {
  const existingIndex = attachments.value.findIndex((att) => att.id === item.id);

  if (existingIndex !== -1) {
    attachments.value[existingIndex].count += item.count;
  } else {
    attachments.value.push(item);
  }

  HandDrawnNotification.success({
    title: "已添加",
    message: `${item.name} x${item.count}`,
  });
};

const removeAttachment = async (index: number) => {
  const item = attachments.value[index];
  try {
    const confirmed = await HandDrawnMessageBox.warning(
      `确定要移除 ${item.name} 吗？`,
      "确认移除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }
    );

    if (confirmed) {
      attachments.value.splice(index, 1);
      HandDrawnNotification.info({
        title: "已移除",
        message: `${item.name}`,
      });
    }
  } catch (error) {
    // 用户取消，不做任何操作
  }
};

const sendMail = async () => {
  try {
    await mailFormRef.value.validate();

    sending.value = true;

    // 构建附件数据
    const items = attachments.value.map((att) => ({
      id: att.id,
      type: att.type,
      cont: att.count,
    }));

    // 调用邮件发送接口
    const result = await callApi("mail/Send", {
      title: mailForm.title,
      to_id: mailForm.recipient,
      msg: mailForm.content,
      items: items,
    });

    if (result) {
      ElMessage.success("邮件发送成功！");

      // 清空表单
      mailForm.recipient = "";
      mailForm.title = "";
      mailForm.content = "";
      attachments.value = [];

      // 返回首页
      router.push("/");
    }
  } catch (error) {
    console.error("发送邮件失败:", error);
    ElMessage.error("发送邮件失败，请重试");
  } finally {
    sending.value = false;
  }
};
</script>

<style lang="scss" scoped>
.send-mail-page {
  position: relative;
  min-height: 100vh;

  .card {
    margin-top: 10px;
  }
}

.attachment-section {
  width: 100%;
}

.attachment-list {
  margin-bottom: 15px;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  margin-bottom: 8px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 8px;
  border: 1px solid #e0e0e0;

  .item-info {
    display: flex;
    align-items: center;
    gap: 8px;

    .item-icon {
      color: #409eff;
      font-size: 16px;
    }

    .item-name {
      font-weight: 500;
      color: #333;
    }

    .item-count {
      color: #666;
      font-size: 12px;
      background: #f0f0f0;
      padding: 2px 6px;
      border-radius: 4px;
    }
  }
}

.add-attachment-btn {
  width: 100%;
  height: 50px;
  border-style: dashed;
  border-width: 2px;
  background: rgba(64, 158, 255, 0.05);
  color: #409eff !important;
  font-weight: 500;

  &:hover {
    background: rgba(64, 158, 255, 0.1);
    color: #337ecc !important;
  }
}

.send-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: bold;
  color: white !important;
}

.center {
  text-align: center;
  margin-top: 20px;
}

.attachment-item {
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
